package com.newa.actions;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.imgscalr.Scalr;

import com.newa.beans.Work;
import com.newa.dao.DAOWorks;
import com.newa.listeners.Listener;
import com.newa.utils.HibUtil;
import com.opensymphony.xwork2.ActionSupport;

public class updateWork extends ActionSupport {
	private Logger LOG = Logger.getLogger(Listener.class);
	private int work_id;
	private File[] photos;
	private String[] photosFileNames;
	private String[] photosContentTypes;
	private File logo;
	private String logoFileName;
	private String logoContentType;
	Work work;

	public BufferedImage getResizedInage(File file) throws IOException{
		BufferedImage img = ImageIO.read(file);

		float w = img.getWidth(); w = w/(float)(3.625);
		float h = img.getHeight(); h = h/(float)(3.64516129);
		BufferedImage res = Scalr.resize(img, (int)w, (int)h, null);
		return res;
	}
	
	public String getType(String mime){
		StringTokenizer tok = new StringTokenizer(mime,"/");
		tok.nextToken();
		String res = tok.nextToken();
		return res;
	}
	
	@Override
	public String execute() throws Exception {
		Session session = HibUtil.getSessionFactory().openSession();
		DAOWorks daow = new DAOWorks(session);
		try {
			Work www = daow.getWorkById(work_id);
			work.setSECTION_ID(www.getSECTION_ID());
			work.setID(work_id);
			work.setLOGO_LINK(www.getLOGO_LINK());
			work.setPHOTO_LINKS(www.getPHOTO_LINKS());
			work.setLPHOTO_LINKS(www.getLPHOTO_LINKS());
			session.clear();
			session.flush();
			if (photos != null) {
				String pl = work.getPHOTO_LINKS();
				String lpl = work.getLPHOTO_LINKS();
				if (pl != null && pl != "") {
					StringTokenizer tok = new StringTokenizer(pl, ";");
					StringTokenizer ltok = new StringTokenizer(lpl, ";");
					while (tok.hasMoreElements()) {
						String pa = (String) tok.nextElement();
						String lpa =  ltok.nextToken();
						File d = new File(pa);
						File ld = new File(lpa);
						d.delete();
						ld.delete();
					}
				}
				work.setPHOTO_LINKS(null);
				work.setLPHOTO_LINKS(null);
				String path = ServletActionContext.getServletContext()
						.getRealPath("/photos");
				
				String plinks = "";
				String lplinks = "";
				BufferedImage res;
				for (int i = 0; i < photos.length; i++) {
					File ph = photos[i];
					File phToCreate = new File(path, photosFileNames[i]);
					FileUtils.copyFile(photos[i], phToCreate);
					res = getResizedInage(new File(path+"/"+photosFileNames[i]));
					File outputfile = new File(path+"/"+"l"+photosFileNames[i]);
				    ImageIO.write(res, getType(photosContentTypes[i]), outputfile);
					plinks += path + "/" + photosFileNames[i] + ";";
					lplinks += path+"/"+"l"+photosFileNames[i]+";";
				}
				plinks = plinks.substring(0, plinks.length() - 1);
				lplinks = lplinks.substring(0, lplinks.length() - 1);
				work.setPHOTO_LINKS(plinks);
				work.setLPHOTO_LINKS(lplinks);
			}
			
			if (logo != null) {
				String ll = work.getLOGO_LINK();
				if (ll != null && ll != "") {
					File d = new File(ll);
					d.delete();
				}
				String path = ServletActionContext.getServletContext()
						.getRealPath("/photos");
				File logoToCreate = new File(path, logoFileName);
				FileUtils.copyFile(logo, logoToCreate);
				work.setLOGO_LINK(path + "/" + logoFileName);
			}
			daow.updateWork(work);
		} catch (Exception e) {
			LOG.warn(e);
			throw new RuntimeException(e);
		} finally {
			daow.closeSession().close();
		}
		return "success";
	}

	public String prepare() {
		Session session = HibUtil.getSessionFactory().openSession();
		DAOWorks daow = new DAOWorks(session);
		try {
			Work wwrk = daow.getWorkById(work_id);
			setWork(wwrk);
		} catch (Exception e) {
			LOG.warn(e);
			throw new RuntimeException(e);
		} finally {
			daow.closeSession().close();
		}
		return "prepare";
	}

	public int getWork_id() {
		return work_id;
	}

	public void setWork_id(int work_id) {
		this.work_id = work_id;
	}

	public File[] getPhotos() {
		return photos;
	}

	public void setPhotos(File[] photos) {
		this.photos = photos;
	}

	public File getLogo() {
		return logo;
	}

	public void setLogo(File logo) {
		this.logo = logo;
	}

	public Work getWork() {
		return work;
	}

	public void setWork(Work work) {
		this.work = work;
	}

	public void setPhotosFileName(String[] photosFileNames) {
		this.photosFileNames = photosFileNames;
	}

	public void setPhotosContentType(String[] photosContentTypes) {
		this.photosContentTypes = photosContentTypes;
	}

	public void setLogoFileName(String logoFileName) {
		this.logoFileName = logoFileName;
	}

	public void setLogoContentType(String logoContentType) {
		this.logoContentType = logoContentType;
	}

	public String[] getPhotosContentType() {
		return photosContentTypes;
	}

	public String[] getPhotosFileName() {
		return photosFileNames;
	}

	public String getLogoFileName() {
		return logoFileName;
	}

	public String getLogoContentType() {
		return logoContentType;
	}
}
